from ETP.models import Step
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from .UIError import UIError
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class SeleniumUtil():

    __operation = 'OpenBrowser'
    __locateMethod = 'XPATH'
    __locateUrl = '/'
    __data = ''
    __chromeDriver = '../../bin/chromedriver.exe'

    def __init__(self):
        self.driver = webdriver.Chrome(executable_path=self.__chromeDriver)
        self.Element = None
        self.step = None

    def run_step(self,step_id):
        self.step = Step.objects.get(id = step_id)
        self.__operation = self.step.ui_operation
        self.__locateMethod = self.step.ui_locate_method
        self.__locateUrl = self.step.ui_locate_url
        self.__data = self.step.ui_data

    def OpenBrowser(self):
        try:
            self.driver.get(self.__data)
        except:
            raise UIError('打开目标网址失败，请验证网址是否可用')

    def Click(self):
        try:
            self.Element = self.FindElement()
            self.Element.click()
        except:
            raise UIError('点击元素失败，查看页面加载或定位url')

    def Type(self):
        try:
            self.Element = self.FindElement()
            self.Element.send_keys(self.__data)
        except:
            raise UIError('输入元素失败，查看页面加载或定位url')

    def Check(self):
        try:
            self.Element = self.FindElement()
            UIText = self.Element.text
        except:
            raise UIError('检查元素失败，查看页面加载或定位url')
        try:
            assert UIText.strip() == self.__data
        except:
            raise UIError('数据比对出现异常，请查数据是否一致')

    def CloseBrowser(self):
        self.driver.close()

    def FindElement(self):
        if self.__locateMethod == 'ID':
            try:
                self.elem = WebDriverWait(self.driver, 30).until(
                    lambda driver: self.driver.find_element(By.ID, self.__locateUrl))
                return self.elem
            except:
                raise UIError('定位的元素没有出现，查看元素是否编写正确')
        elif self.__locateMethod == 'NAME':
            try:
                self.elem = WebDriverWait(self.driver, 30).until(
                    lambda driver: self.driver.find_element(By.NAME, self.__locateUrl))
                return self.elem
            except:
                raise UIError('定位的元素没有出现，查看元素是否编写正确')
        elif self.__locateMethod == 'XPATH':
            try:
                self.elem = WebDriverWait(self.driver, 30).until(
                    lambda driver: self.driver.find_element(By.XPATH, self.__locateUrl))
                return self.elem
            except:
                raise UIError('定位的元素没有出现，查看元素是否编写正确')
        else:
            return None
